package com.fortune.cat.utils;

import com.fortune.cat.bean.DegradeConfig;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.ORIGINAL_RESPONSE_CONTENT_TYPE_ATTR;

/**
 * @author zhaozeyang
 * @date 2019/4/11 15:54
 * @description
 */
public class ServerResponseUtils {

    /**
     * 设置返回
     *
     * @param returnStr
     * @param exchange
     * @param httpStatus
     * @return
     */
    public static Mono<Void> returnCommonResponse(String returnStr, ServerWebExchange exchange, HttpStatus httpStatus) {
        DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
        DataBuffer buffer = dataBufferFactory.allocateBuffer(2);
        exchange.getResponse().setStatusCode(httpStatus);
        buffer.write(returnStr.getBytes());
        exchange.getAttributes().put(ORIGINAL_RESPONSE_CONTENT_TYPE_ATTR, MediaType.APPLICATION_JSON_UTF8_VALUE);
        return exchange.getResponse().writeWith(Flux.just(buffer));
    }

    public static Mono<Void> ReturnCommonResponse(DegradeConfig.ReturnInfo commonReturnInfo, ServerWebExchange exchange) {
        return returnCommonResponse(commonReturnInfo.getCommonReturnJson(), exchange, HttpStatus.resolve(commonReturnInfo.getHttpStatus()));

    }
}
